package com.sonicvision.resourcetracker.mailmerge;

import java.io.ByteArrayInputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MailMergeController {

	@Autowired
	private MailSender mailSender;

	@RequestMapping(value = "/mailmerge", method = RequestMethod.GET)
	public ModelAndView getMailMergeUploadForm() {

		ModelAndView modelAndView = new ModelAndView("MailMerge");
		modelAndView.addObject("fileUpload", new FileUpload());

		return modelAndView;
	}

	@RequestMapping(value = "/mailmerge", method = RequestMethod.POST)
	public String sendEmail(@ModelAttribute FileUpload fileUpload)
			throws Exception {

		MultipartFile contactsFile = fileUpload.getContactsFile();
		MultipartFile resume = fileUpload.getResume();

		byte[] contactsFileBytes = contactsFile.getBytes();
		byte[] resumeBytes = resume.getBytes();

		ByteArrayInputStream baos = new ByteArrayInputStream(contactsFileBytes);
		ExcelReader reader = new ExcelReader();
		List<Contact> contacts = reader.getContactsFromExcel(baos);

		ByteArrayInputStream contactsFileBIOS2 = new ByteArrayInputStream(
				contactsFileBytes);

		ByteArrayInputStream resumeBAIS = new ByteArrayInputStream(resumeBytes);

		mailSender.sendMail(contactsFileBIOS2, contacts, resumeBAIS,
				resume.getOriginalFilename());

		return "MailMerge";
	}

}
